package mydb.backend.dm.page;

import mydb.backend.dm.pageCache.PageCache;
import mydb.backend.utils.RandomUtil;

import java.util.Arrays;

/**
 * 特殊管理第一页
 * ValidCheck
 * db启动时给100-107字节处填入一个随机字节，db关闭时将其拷贝到108~115字节
 * @author Fang Ruichuan
 * @date 2023-03-06 22:42
 */
public class PageOne {
    private static final int OF_VC = 100;
    private static final int LEN_VCC = 8;

    public static byte[] initRaw() {
        return new byte[PageCache.PAGE_SIZE];
    }

    public static void setVcOpen(Page pg) {
        pg.setDirty(Boolean.TRUE);
        setVcOpen(pg.getData());
    }

    private static void setVcOpen(byte[] raw) {
        System.arraycopy(RandomUtil.randomBytes(LEN_VCC), 0, raw, OF_VC, LEN_VCC);
    }

    public static void setVcClose(Page pg) {
        pg.setDirty(true);
        setVcClose(pg.getData());
    }

    private static void setVcClose(byte[] raw) {
        System.arraycopy(raw, OF_VC, raw, OF_VC+LEN_VCC, LEN_VCC);
    }

    public static boolean checkVc(Page pg) {
        return checkVc(pg.getData());
    }

    private static boolean checkVc(byte[] raw) {
        return Arrays.equals(Arrays.copyOfRange(raw, OF_VC, OF_VC+LEN_VCC), Arrays.copyOfRange(raw, OF_VC+LEN_VCC, OF_VC+2*LEN_VCC));
    }
}
